package baohuajie.com.algorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author goujian
 * @description: TODO
 * @date 2022/3/2 6:15 下午
 */
@Slf4j
public class DateRangeAlgorithm implements RangeShardingAlgorithm<LocalDateTime> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<LocalDateTime> shardingValue) {
        LocalDateTime lowerEndpoint = shardingValue.getValueRange().lowerEndpoint();
        LocalDateTime upperEndpoint = shardingValue.getValueRange().upperEndpoint();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        Long lowerEndpointLong = Long.valueOf(lowerEndpoint.format(formatter));
        Long upperEndpointLong = Long.valueOf(upperEndpoint.format(formatter));
        List<String> content_ = availableTargetNames.stream().map(e -> {
            return e.split("content_")[1];
        }).collect(Collectors.toList());
        List<String> collect = content_.stream().map(targetName -> Long.valueOf(targetName))
                .filter(e -> e >= lowerEndpointLong && e <= upperEndpointLong)
                .map(a -> "content_" + String.valueOf(a))
                .collect(Collectors.toList());
        return collect;
    }
}
